package com.linkage.jz.bankruptcy.activity.Project;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.CommonTabPagerAdapter;
import com.linkage.jz.bankruptcy.bean.AddressInfo;
import com.linkage.jz.bankruptcy.bean.ManagerBaseUserInfo;
import com.linkage.jz.bankruptcy.bean.ManagerUserInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.bean.OtherBaseUserInfo;
import com.linkage.jz.bankruptcy.fragment.Project.ManagerUserBaseDetailFragment;
import com.linkage.jz.bankruptcy.fragment.Project.OtherUserBaseDetailFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProFlowFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProTaskFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProPublicFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProTalkFragment;
import com.linkage.jz.bankruptcy.fragment.Project.ProVoteFragment;
import com.linkage.jz.bankruptcy.fragment.Project.RelationProjectFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PopupMenuPublicPro;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.activity.chat.ChatDetailActivity;
import com.linkage.seapeak.base.BaseActivity;
import com.linkage.seapeak.utils.MenuBottomSheetDialog;
import com.linkage.seapeak.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;


public class ManagerUserDetailActivity extends BaseActivity implements CommonTabPagerAdapter.TabPagerListener {

    Toolbar toolbar;
    CollapsingToolbarLayout collapsingToolbar;
    TabLayout tabLayout;
    AppBarLayout appbar;
    ViewPager viewpager;
    //    TextView tv_proname,tv_managename,tv_manageaddr,tv_manageuser;
    ImageView iv_proimg;


    private CommonTabPagerAdapter adapter;
    private ManagerUserInfo mInfo;

    private ManagerBaseUserInfo.UserAuth auth;
    private TextView tv_username, tv_userorg, tv_userterm;

    ManagerUserBaseDetailFragment infoFragment;
    PublicNoticeDialog noticeDialog;

    MenuItem menuItem;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.manageruser_menu_scrolling, menu);
        menuItem = menu.findItem(R.id.action_settings);

        if(mInfo.getUserAuth()!=null)
        {
            if (auth.isSetMemberPermissions()||auth.isDeleteManagementMembers())
            {
                menuItem.setVisible(true);
            }else{
                menuItem.setVisible(false);
            }
        }else {
            menuItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_settings) {
            showDialog();
            return true;
        } else
            return super.onOptionsItemSelected(item);
    }

    private void showDialog() {
        PopupMenuPublicPro popupMenu;
        popupMenu = new PopupMenuPublicPro(this);
            ArrayList<String> ary = new ArrayList<String>();


        if (auth.isSetMemberPermissions()) {
            ary.add("查看权限");
            ary.add("成员角色权限配置");
        }
        if (auth.isDeleteManagementMembers())
            ary.add( "移除该成员");
            popupMenu.initData(ary);
//        }
        popupMenu.showLocation(R.id.action_settings);
        // 设置回调监听，获取点击事件
        popupMenu.setOnItemClickListener(new PopupMenuPublicPro.OnItemClickListener() {

            @Override
            public void onClick(PopupMenuPublicPro.MENUITEM item, String str) {
                if ("查看权限".equalsIgnoreCase(str)) {
                    ManagerUserPermissionActivity.start(ManagerUserDetailActivity.this, mInfo, false);
                }

                if ("成员角色权限配置".equalsIgnoreCase(str)) {
                    ManagerUserPermissionActivity.start(ManagerUserDetailActivity.this, mInfo, true);
                }

                if ("移除该成员".equalsIgnoreCase(str)) {
                    noticeDialog = new PublicNoticeDialog(ManagerUserDetailActivity.this, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.btn_save_notice) {
                                delUser(mInfo.getId());
                            }
                            noticeDialog.dismiss();
                        }
                    }, 1, "提示", "确认删除么？",
                            "取消", "确认");
                    noticeDialog.show();
                }
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarMode(false);
        setContentView(R.layout.activity_manageruser_detail);
        String bookJson = getIntent().getStringExtra("info");
        mInfo = new Gson().fromJson(bookJson, ManagerUserInfo.class);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        viewpager = (ViewPager) findViewById(R.id.viewpager);

        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_userorg = (TextView) findViewById(R.id.tv_userorg);
        tv_userterm = (TextView) findViewById(R.id.tv_userterm);
        iv_proimg = (ImageView) findViewById(R.id.iv_proimg);

        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        setTitle("");
        collapsingToolbar.setTitle("");
        collapsingToolbar.setExpandedTitleColor(Color.parseColor("#00ffffff"));//设置还没收缩时状态下字体颜色
        collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);//设置收缩后Toolbar上字体的
        adapter = new CommonTabPagerAdapter(getSupportFragmentManager()
                , 2, Arrays.asList("基础信息", "关联项目"), this);
        adapter.setListener(this);
        viewpager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewpager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //在这里执行我们的逻辑代码
                finish();
            }
        });
        infoFragment = ManagerUserBaseDetailFragment.newInstance();
        setData();
    }

    public void setData() {
        if (mInfo != null) {
            tv_username.setText(mInfo.getName());
            tv_userorg.setText(mInfo.getSubsidiaryOrgan());
            tv_userorg.setVisibility(TextUtils.isEmpty(mInfo.getSubsidiaryOrgan()) ? View.GONE : View.VISIBLE);
            tv_userterm.setText(mInfo.getGroup().getName());
            String url = mInfo.getUser().getAvatar();
            Glide.with(this).load(url)
                    .bitmapTransform(new CropCircleTransformation(this))
                    .placeholder(R.drawable.logo)
                    .into(iv_proimg);

            findViewById(R.id.iv_email).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ChatDetailActivity.start(ManagerUserDetailActivity.this, mInfo.getUser().getId(),
                            mInfo.getName(), mInfo.getBankruptcyProjectId());
                }
            });

//            findViewById(R.id.iv_email).setVisibility(mInfo.getContactCreditor() ? View.VISIBLE : View.GONE);
            findViewById(R.id.iv_phone).setVisibility(mInfo.isHidePhone() ? View.GONE : View.VISIBLE);

            findViewById(R.id.iv_phone).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mInfo.getUser() != null || !TextUtils.isEmpty(mInfo.getUser().getMobile())) {
                        final String phone = mInfo.getUser().getMobile();
                        SetPhone(phone);
                        noticeDialog = new PublicNoticeDialog(ManagerUserDetailActivity.this, new View.OnClickListener(){

                            @Override
                            public void onClick(View v) {
                                switch (v.getId()) {
                                    case R.id.ll_close:
                                        noticeDialog.dismiss();
                                        break;
                                    case R.id.btn_chancel_notice:

                                        if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_SMS_PERMISSION)){

                                            try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                                Intent intent = new Intent(Intent.ACTION_SENDTO);
                                                Uri data = Uri.parse("smsto:" + phone);
                                                intent.setData(data);
                                                startActivity(intent);

//                                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
//                                                intent.putExtra("sms_body", message);
//                                                startActivity(intent);

                                            }catch (Exception ex){
                                                ex.printStackTrace();
                                            }
                                        }
                                        noticeDialog.dismiss();
                                        break;

                                    case R.id.btn_save_notice:
                                        if(!"".equalsIgnoreCase(phone)) {
                                            if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                                                try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                                    Intent intent = new Intent(Intent.ACTION_CALL);
                                                    Uri data = Uri.parse("tel:" + phone);
                                                    intent.setData(data);
                                                    startActivity(intent);
                                                }catch (Exception ex){
                                                    ex.printStackTrace();
                                                }
                                            }
                                        }
                                        noticeDialog.dismiss();

                                        break;
                                }
                            }
                        }, 2,phone, phone,"发短信","拨打电话");
                        noticeDialog.show();
                    } else
                        showToast("无法获取号码");
                }
            });

            findViewById(R.id.admin_tip).setVisibility((mInfo.getProjectRole() != null &&
                    mInfo.getProjectRole().getValue() == 102) ? View.VISIBLE : View.GONE);
            findViewById(R.id.leader_tip).setVisibility(mInfo.getGroupLeader() ? View.VISIBLE : View.GONE);
//            findViewById(R.id.admin_tip).setVisibility( View.GONE);
//            findViewById(R.id.leader_tip).setVisibility( View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getUserInfo();
            }
        }, 20);
    }

    public void getUserInfo() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        Network.getAPIService()
                .getManagerMemberInfo(mInfo.getId(), getUserToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            if(json.get("code").getAsInt() == 0) {
                                String jsonStr = json.getAsJsonObject("data").toString();
                                ManagerBaseUserInfo item = new Gson().fromJson(jsonStr, ManagerBaseUserInfo.class);
                                mInfo = item.getManagersInfo();
                                auth =new Gson().fromJson(json.getAsJsonObject("data").getAsJsonObject("auth").toString(), ManagerBaseUserInfo.UserAuth.class);

                                if (!auth.isOpenAdministratorInfo()) {
                                    showToast("暂无权限查看详情！");
                                    finish();
                                    return;
                                }

                                mInfo.setUserAuth(auth);
                                setData();
                                infoFragment.setInfo(mInfo);
                                infoFragment.setPermissionParms(auth, item.getManagersInfo().isHidePhone());

                                if (menuItem == null)
                                    return;
                                if("负责人".equalsIgnoreCase(mInfo.getProjectRole().getText()) ||
                                        "管理员".equalsIgnoreCase(mInfo.getProjectRole().getText())) {
                                    menuItem.setVisible(true);
                                } else
                                    menuItem.setVisible(false);

//                                if (auth.isSetMemberPermissions()||auth.isDeleteManagementMembers()) {
//
//                                    findViewById(R.id.admin_tip).setVisibility((mInfo.getProjectRole() != null &&
//                                            mInfo.getProjectRole().getValue() == 102) ? View.VISIBLE : View.GONE);
//                                    findViewById(R.id.leader_tip).setVisibility(mInfo.getGroupLeader() ? View.VISIBLE : View.GONE);
//                                }else{
//                                    findViewById(R.id.admin_tip).setVisibility( View.GONE);
//                                    findViewById(R.id.leader_tip).setVisibility( View.GONE);
//                                }
                                supportInvalidateOptionsMenu();
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    @Override
    public Fragment getFragment(int position) {
        switch (position) {
            case 0:
                return infoFragment;
            case 1:
                return RelationProjectFragment.newInstance(mInfo);
            case 2:
//                return ProZQFragment.newInstance(position,mInfo.getId(),mInfo);
//                break;
            case 3:
                return ProVoteFragment.newInstance(position, mInfo.getId());

            case 4:
                return ProTalkFragment.newInstance(position, mInfo.getId());
            case 5:
                return ProTaskFragment.newInstance(position, mInfo.getId());
            case 6:
                return ProPublicFragment.newInstance(position, mInfo.getId());
            default:

                return ProFlowFragment.newInstance(position, mInfo.getId());
//                    break;
        }
    }

    public void delUser(String userId) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showProgress("加载中");
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
//        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("managersTeamId", userId)
                .build();

        String url = Consts.WEBURL_DELETEMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        hideProgress();
                        showToast("删除失败");
                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }

                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                hideProgress();
                                showToast("删除成功", ToastUtil.TOAST_TYPE.SUCCESS);
                                finish();
                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                hideProgress();
                                showToast("删除失败");
                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            hideProgress();
                            showToast("删除失败");
                        }

                    });
                }
            }
        });
    }

}
